from django.db.models.signals import post_syncdb
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission, Group


def add_view_permissions(sender, **kwargs):
    """
    http://blog.nyaruka.com/adding-a-view-permission-to-django-models
    This syncdb hooks takes care of adding a view permission too all our
    content types.
    """
    # for each of our content types
    for content_type in ContentType.objects.filter(
                                    app_label=u'django_moneyguard').distinct():
        # build our permission slug
        codename = "view_%s" % content_type.model
        if (content_type.app_label == u'django_moneyguard' and
                not Permission.objects.filter(content_type=content_type,
                                              codename=codename)):
            # add it
            Permission.objects.create(content_type=content_type,
            codename=codename,
            name="Can view %s" % content_type.name, )
            print "Added view permission for %s for app: %s" % (
                                    content_type.name, content_type.app_label)


def is_permission_in_group(permission, group):
    for group_permission in group.permissions.all():
        if permission.id == group_permission.id:
            return True
    return False


def add_groups(sender, **kwags):
    tupleCreate = Group.objects.get_or_create(name='familyAdmin')
    family_admin_group = tupleCreate[0]
    if tupleCreate[1]:
        print('new group added:' + family_admin_group.name)
    for permission in Permission.objects.all():
        if (permission.content_type.app_label == u'django_moneyguard'
                and not is_permission_in_group(
                                    permission, family_admin_group)):
            family_admin_group.permissions.add(permission)
            print(
                ' - Group'
                + family_admin_group.name
                + ' new permission added: '
                + permission.codename
            )
    family_admin_group.save()


def run_tasks(sender, **kwags):
    add_view_permissions(sender)
    add_groups(sender)

# check for all our view permissions after a syncdb
post_syncdb.connect(run_tasks)
